<!-- 选择资源弹窗 -->
<template>
  <div class="choose-repertory">
    <el-dialog :title="title" :visible.sync="dialogTableVisible" :modal-append-to-body="false"
      :close-on-click-modal="false" :width="width" @closed="closed">
      <div class="repertory" v-loading="loading">
        <el-row type="flex" justify="space-between">
          <div class="left">
            <el-form :inline="true" :model="where" ref="repertorySearch" class="demo-form-inline"
              @submit.native.prevent>
              <el-form-item label="标签" style="margin-bottom:0;" prop="labelId">
                <el-select v-model="where.labelId" placeholder="选择资源的标签" size="mini" style="width:160px;"
                  :disabled="fixedCondition.labelId">
                  <el-option label="全部标签" :value="-1"></el-option>
                  <el-option label="未定义" :value="0"></el-option>
                  <el-option v-for="item in labels" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="类型" style="margin-bottom:0;" prop="type">
                <el-select v-model="where.type" multiple placeholder="选择资源的类型" size="mini">
                  <el-option v-for="item in repertoryType" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                  <!-- <el-option label="图片" :value="0"></el-option>
                  <el-option label="文件" :value="1"></el-option>
                  <el-option label="Flash" :value="2"></el-option>
                  <el-option label="音频" :value="3"></el-option>
                  <el-option label="视频" :value="5"></el-option>
                  <el-option label="外链图片" :value="4"></el-option> -->
                </el-select>
              </el-form-item>
              <el-form-item label="名称" style="margin-bottom:0;" prop="originalFilename"
                :disabled="fixedCondition.originalFilename">
                <el-input v-model="where.originalFilename" placeholder="资源名称" size="mini"
                  @keyup.enter.native="onSearch('repertorySearch')" maxlength="100"></el-input>
              </el-form-item>
              <el-form-item style="margin-bottom:0;">
                <el-button type="primary" @click="onSearch('repertorySearch')" size="mini">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-row>
        <!-- 资源列表 -->
        <el-row type="flex" justify="start">
          <div class="list">
            <div v-if="list.length < 1" class="no-data">暂无数据~~</div>
            <div class="item" v-for="item in list" :key="item.id" @click.stop="selectItem(item.id)">
              <div :class="{'item-top':true,cur: isExistItem(item.id)}">
                <div class="img">
                  <img :src="src(item.id)" :alt="item.originalFilename" />
                </div>
                <div class="tick noselect" v-if="isExistItem(item.id)">
                  <i class="icon iconfont icon-duigou"></i>
                </div>
                <div class="pixel">
                  {{item.pixel | showPixel}}
                </div>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.originalFilename" placement="top">
                <div class="title textnowrap">
                  {{item.originalFilename}}
                </div>
              </el-tooltip>
            </div>
          </div>
        </el-row>
        <!-- 信息 -->
        <el-row type="flex" justify="space-between">
          已选中{{selection.length}}个资源，总共可以选择{{max}}个资源
        </el-row>
        <!-- 分页 -->
        <el-row type="flex" justify="end">
          <PageTurning ref="pageTurning" :changePage="changePage" :page="pagination" />
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click.stop="addOutsideImageLink" size="mini">添加外链图片</el-button>
        <el-button type="success" v-loading="uploadLoading" @click.stop="upload" size="mini">上 <i
            class="el-icon-upload"></i>
          传</el-button>
        <el-button type="primary" @click.stop="ok" size="mini">确 定</el-button>
        <el-button @click="dialogTableVisible = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <RepertoryUpload ref="repertoryUpload" :finish="complete" />
    <AddOutsideImageLink :getLink="submitOutsideImageLink" ref="addOutsideImageLink" />
  </div>
</template>

<script>
import RepertoryUpload from '@/components/common/upload/RepertoryUpload.vue'
import AddOutsideImageLink from '@/components/main/user/repertory/dialog/AddOutsideImageLink.vue'
import PageTurning from '@/components/common/PageTurning.vue'
import * as functions from '@/core/functions.js'
export default {
  computed: {
    repertoryType1: function () {
      let repType = [
        {
          value: -1, label: '所有类型'
        },
        {
          value: 0, label: '图片'
        },
        {
          value: 1, label: '文件'
        },
        {
          value: 2, label: 'Flash'
        },
        {
          value: 3, label: '音频'
        },
        {
          value: 5, label: '视频'
        },
        {
          value: 4, label: '外链图片'
        },
        {
          value: 6, label: 'SSL文件'
        }
      ]

      return repType
    }
  },
  created () {
    // 获取文件可以上传的后缀
    this.$post('/upload/allow-ext').then((response) => {
      // uploadLoading
      this.uploadInfos = response
      this.uploadInfosAll = JSON.parse(JSON.stringify(response))
      this.uploadLoading = false
    })
    // 获取所有的标签
    this.$post('/repertory/all-label').then((response) => {
      this.labels = response
    })
  },
  data () {
    return {
      // 上传按钮 loading
      uploadLoading: true,
      // 是否显示
      dialogTableVisible: false,
      // 加载资源数据
      loading: false,
      // 显示宽度
      width: '950px',
      // 显示标题
      title: '',
      // 查询条件
      where: {
        labelId: -1,
        type: [-1],
        originalFilename: ''
      },
      // 查询条件的列表
      repertoryType: [],
      // 是否固定条件
      fixedCondition: {
        labelId: false,
        type: false,
        originalFilename: false
      },
      // 可选个数
      max: 1,
      // 分页
      pagination: { page: 1, size: 12, total: 0 },
      // 回调函数
      callback: null,
      // 允许上传的后缀原始值
      uploadInfosAll: [],
      // 允许上传的后缀
      uploadInfos: [],
      // 所有的标签
      labels: [],
      // 数据
      list: [],
      // 选中的资源
      selection: []
    }
  },
  watch: {
    where: {
      handler (newValue) {
        let type = JSON.parse(JSON.stringify(newValue.type))
        // 是否为空
        if (type.length === 0) {
          // 是否存在 -1
          let item = this.repertoryType.find(element => {
            return parseInt(element.value) === -1
          })
          if (item) {
            this.where.type = [-1]
          } else {
            let t = this.repertoryType.map(elem => {
              return parseInt(elem.value)
            })
            this.where.type = t
          }
        } else if (type.length === 1 && type[0] === -1) {
        } else {
          // 是否存在 -1
          let index = type.findIndex(item => {
            return item === -1
          })
          if (index > -1) {
            type.splice(index, 1)
            this.where.type = type
          }
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取数据
    getData () {
      let param = Object.assign({}, this.where, this.pagination)
      this.loading = true
      this.$jpost('/repertory/find', param).then(response => {
        if (response && response.total > 0) {
          this.pagination.total = response.total
          this.list = response.list
        } else {
          this.list = []
          this.pagination.total = 0
        }
        this.loading = false
      })
    },
    // 当分页改变
    changePage (page) {
      this.pagination = JSON.parse(JSON.stringify(page))
      this.getData()
    },
    // 显示图片的路径
    src (id) {
      let item
      for (let i in this.list) {
        if (this.list[i].id === id) {
          item = this.list[i]
          break
        }
      }
      if (!item) {
        return ''
      }
      return functions.getRepertoryImageSrc({ hostId: this.$store.state.host.id, repertoryId: id, suffix: item.suffix, type: item.type, link: item.link })
    },
    // 显示
    show (obj, callback) {
      if (obj) {
        if (obj.title) {
          this.title = obj.title
        }
        if (obj.max) {
          this.max = obj.max
        }
        if (obj.where) {
          let where = this.where
          if (typeof obj.where.labelId !== 'undefined') {
            where.labelId = obj.where.labelId
          }
          if (typeof obj.where.type !== 'undefined') {
            where.type = obj.where.type
          }
          if (typeof obj.where.originalFilename !== 'undefined') {
            where.originalFilename = obj.where.originalFilename
          }
          if (typeof obj.where.suffix !== 'undefined') {
            where.suffix = obj.where.suffix
          }
          this.where = JSON.parse(JSON.stringify(where))
        }

        if (this.where.type) {
          this.repertoryType = getRepertoryType(this.where.type)
          this.uploadInfos = JSON.parse(JSON.stringify(filterUploadInfos(this.uploadInfosAll, this.where.type)))
        } else {
          this.repertoryType = getRepertoryType([-1])
          this.uploadInfos = JSON.parse(JSON.stringify(this.uploadInfosAll))
        }
        if (this.where.suffix) {
          for (let i in this.uploadInfos) {
            let ext = this.uploadInfos[i].ext
            let temp = []
            for (const val of this.where.suffix) {
              let index = ext.find(item => item === val)
              if (index) {
                temp.push(val)
              }
            }
            if (temp.length > 0) {
              this.uploadInfos[i].ext = temp
            }
          }
        }

        if (obj.fixedCondition) {
          let fixedCondition = this.fixedCondition
          if (typeof obj.fixedCondition.labelId !== 'undefined') {
            fixedCondition.labelId = obj.fixedCondition.labelId
          }
          if (typeof obj.fixedCondition.type !== 'undefined') {
            fixedCondition.type = obj.fixedCondition.type
          }
          if (typeof obj.fixedCondition.originalFilename !== 'undefined') {
            fixedCondition.originalFilename = obj.fixedCondition.originalFilename
          }
          this.fixedCondition = JSON.parse(JSON.stringify(fixedCondition))
        }
        if (obj.pagination) {
          let pagination = this.pagination
          if (typeof obj.pagination.page !== 'undefined') {
            pagination.page = obj.pagination.page
          }
          if (typeof obj.pagination.size !== 'undefined') {
            pagination.size = obj.pagination.size
          }
          this.pagination = JSON.parse(JSON.stringify(pagination))
        } else {
          let pagination = this.pagination
          pagination.page = 1
          this.pagination = JSON.parse(JSON.stringify(pagination))
        }

        if (obj.width) {
          this.width = obj.width
        }
        // 显示
        this.dialogTableVisible = true
        if (typeof callback === 'function') {
          this.callback = callback
        }
        // 获取数据
        this.getData()
      }
    },
    // 确认选择的内容
    ok () {
      if (typeof this.callback === 'function') {
        this.callback(this.selection)
      }
      this.dialogTableVisible = false
    },
    // 上传
    upload () {
      if (this.uploadLoading) {
        return
      }
      // 调用子组件RepertoryUpload click() 方法
      this.$refs['repertoryUpload'].click(this.uploadInfos)
    },
    // 上传完成后
    complete (data) {
      this.pagination.page = 1
      this.getData()
      let isAll = this.repertoryType.find(element => {
        return parseInt(element.value) === -1
      })
      let filterData
      if (isAll) {
        filterData = data
      } else {
        filterData = data.filter((item) => {
          let type = item.type
          let index = this.repertoryType.find(ite => parseInt(ite.value) === parseInt(type))
          if (index) {
            return item
          }
        })
      }
      let filterSuffixData
      if (this.where.suffix) {
        filterSuffixData = filterData.filter((item) => {
          let ind = this.where.suffix.find(ite => ite === item.suffix)
          if (ind) {
            return item
          }
        })
      } else {
        filterSuffixData = filterData
      }
      let resData
      if (filterSuffixData.length >= this.max) {
        resData = filterSuffixData.slice(0, this.max)
      } else {
        resData = filterSuffixData
      }
      this.selection = resData
    },
    // 添加外部图片资源链接
    addOutsideImageLink () {
      this.$refs['addOutsideImageLink'].open()
    },
    submitOutsideImageLink (link) {
      this.$post('/repertory/add-outside-image-link', { link: link }).then(response => {
        if (response && response.id > 0) {
          this.getData()
        }
      })
    },
    // 选择的id是否包含在 selection 中
    isExistItem (id) {
      return this.selection.findIndex((item) => {
        return item.id === id
      }) > -1
    },
    // 选择
    selectItem (id) {
      if (this.selection.length >= this.max) {
        // 是否包含
        if (this.isExistItem(id)) {
          this.selection = this.selection.filter((item) => {
            return !(item.id === id)
          })
          return
        }
        if (this.max === 1) {
          this.selection = []
          this.selection.push(this.list.find((item) => {
            return item.id === id
          }))
          return
        }
        this.$message.error('本次只能选择' + this.max + '个资源')
        return
      }
      if (this.selection.length === 0) {
        this.selection.push(this.list.find((item) => {
          return item.id === id
        }))
      } else {
        if (this.isExistItem(id)) {
          this.selection = this.selection.filter((item) => {
            return !(item.id === id)
          })
        } else {
          this.selection.push(this.list.find((item) => {
            return item.id === id
          }))
        }
      }
    },
    // 关闭
    close () {
      // 是否显示
      this.dialogTableVisible = false
      // 显示宽度
      this.width = '950px'
      // 显示标题
      this.title = ''
      // 查询条件
      this.where = {
        labelId: -1,
        type: [-1],
        originalFilename: ''
      }
      // 可选个数
      this.max = 1
      // 分页
      this.pagination = { page: 1, size: 12, total: 0 }
      // 回调函数
      this.callback = null

      // 是否固定条件
      this.fixedCondition = {
        labelId: false,
        type: false,
        originalFilename: false
      }
      // 可选个数
      this.max = 1
      // 数据
      this.list = []
      // 选中的资源
      this.selection = []
    },
    closed () {
      this.close()
    },
    // 搜索
    onSearch (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 获取数据
          this.pagination.page = 1
          this.$refs['pageTurning'].currentPage(1)
          this.getData()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置
    resetSearch (formName) {
      this.$refs[formName].resetFields()
    }
  },
  filters: {
    showPixel (pixel) {
      if (pixel === '0') {
        return ''
      }
      return pixel.replace('X', ' x ')
    }
  },
  components: {
    PageTurning,
    RepertoryUpload,
    AddOutsideImageLink
  }
}

function getRepertoryType (whereType) {
  let repType = [
    {
      value: -1, label: '所有类型'
    },
    {
      value: 0, label: '图片'
    },
    {
      value: 1, label: '文件'
    },
    {
      value: 2, label: 'Flash'
    },
    {
      value: 3, label: '音频'
    },
    {
      value: 5, label: '视频'
    },
    {
      value: 4, label: '外链图片'
    },
    {
      value: 6, label: 'SSL文件'
    }
  ]

  if (!whereType || (whereType.length === 1 && whereType[0] === -1)) {
    return repType
  }

  let res = []
  for (let i in whereType) {
    for (let j in repType) {
      if (parseInt(whereType[i]) === parseInt(repType[j].value)) {
        res.push(repType[j])
      }
    }
  }
  return res
}

function filterUploadInfos (data, whereType) {
  if (!whereType || (whereType.length === 1 && whereType[0] === -1)) {
    return data
  }
  let res = {}
  for (let i in whereType) {
    if (parseInt(whereType[i]) === 0) {
      res['image'] = data['image']
    } else if (parseInt(whereType[i]) === 1) {
      res['file'] = data['file']
    } else if (parseInt(whereType[i]) === 2) {
      res['flash'] = data['flash']
    } else if (parseInt(whereType[i]) === 3) {
      res['audio'] = data['audio']
    } else if (parseInt(whereType[i]) === 5) {
      res['video'] = data['video']
    } else if (parseInt(whereType[i]) === 6) {
      res['ssl'] = data['ssl']
    }
  }
  return res
}
</script>

<style scoped lang="scss">
.list {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
  padding: 0 10px;
  min-height: 200px;

  .no-data {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    color: #888888;
    min-height: 200px;
    text-align: center;
  }

  .item {
    width: 140px;
    margin-right: 8px;
    margin-top: 12px;
    margin-bottom: 6px;

    .img {
      line-height: 140px;

      img {
        max-width: 120px;
        max-height: 120px;
        vertical-align: middle;
      }
    }

    .pixel {
      position: absolute;
      z-index: 1;
      left: 0;
      right: 0;
      bottom: 0;
      padding: 5px 10px;
      text-align: center;
      font-size: 10px;
      background: rgba(210, 210, 210, 0.75);
    }

    .tick {
      position: relative;
      top: -136px;
      left: 4px;
      text-align: left;
      height: 0px;

      .icon {
        display: inline-block;
        border-radius: 100%;
        background-color: #409eff;
        color: #ffffff;
        padding: 2px;
        width: 20px;
        height: 20px;
        line-height: 18px;
        font-size: 12px;
        text-align: center;
      }
    }

    .title {
      text-align: left;
      width: 140px;
      white-space: nowrap;
      height: 20px;
      line-height: 20px;
    }
  }

  .item-top {
    position: relative;
    margin-bottom: 4px;
    text-align: center;
    border: 1px solid #e5e5e5;
    cursor: pointer;
    background-color: #f6f6f6;
    &:hover {
      border-color: #409eff;
    }
  }

  .cur {
    border-color: #409eff;
  }
}
</style>
